package com.shihan.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.shihan.io.Resource;
import com.shihan.pojo.Configuration;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

public class XMLConfiguration {

    private Configuration configuration = null;

    public XMLConfiguration(){
        this.configuration = new Configuration();
    }

    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        // 1、使用 dom4j 解析配置文件的内容；
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> nodes = rootElement.selectNodes("//property");

        Properties properties = new Properties();

        if(nodes!=null&&nodes.size()>0){

            for(Element element:nodes){
                String name = element.attributeValue("name");
                String value = element.attributeValue("value");
                properties.setProperty(name,value);
            }
        }

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        //2、将配置文件中读取出来的内容封装到 Configuration 对象中；
        configuration.setDataSource(comboPooledDataSource);

        // 解析 mapper.xml 文件
        List<Element> selectNodes = rootElement.selectNodes("//mapper");
        if(selectNodes!=null&&selectNodes.size()>0){
            for(Element element:selectNodes){
                String mapperPath = element.attributeValue("resource");
                XMLMapperParse xmlMapperParse = new XMLMapperParse(configuration);
                InputStream is = Resource.getResourceAsStream(mapperPath);
                xmlMapperParse.parse(is);
            }
        }

        return configuration;

    }
}
